package club.pinea.service.impl;

import club.pinea.mapper.UserMapper;
import club.pinea.model.Promoter;
import club.pinea.model.SeatsInfo;
import club.pinea.model.User;
import club.pinea.model.UserInfo;
import club.pinea.service.UserService;
import club.pinea.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author pineapple
 * @date 2017年12月21日 下午3:10:25
 * @description 用户操作接口实现类
 */
@Service("loginUserService")
public class UserServiceImpl implements UserService {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     */
    @Override
    public User userLogin(String username, String password) {
        User u = null;
        try {
            //调用mapper的方法获取user对象比较密码是否一致
            u = userMapper.selectUserByName(username);
            if (u != null && u.getPassword().equals(StringUtils.encode(password + u.getToken()))) {
                if (u.getStatus() == 0) {//正常用户状态为离线
                    return u;
                } else if (u.getStatus() == 3) {//用户暂离
                    return u;
                } else if (u.getStatus() == 1) {//用户在线状态
                    if (u.getLastPlayTime().getTime() + 6000000 < System.currentTimeMillis()) {//判断是否已经十分钟没有操作，如果超过10分钟则可以登陆
                        return u;
                    }
                    logger.error(u.getUsername() + "用户正在其他地方登陆，登录失败！");
                    throw new IllegalStateException("用户正在其他地方登陆，登录失败！");
                } else {
                    logger.error("被封禁的用户：" + u.getUsername() + "正在进行登陆操作");
                    throw new IllegalStateException("您的账号由于异常操作已被封禁！");
                }
            } else {
                return null;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateUserIp(User u, String ip) {
        try {
//			Date d = new Date();
//			if(!(u.getLastPlayTime().getDate()==d.getDate()&&u.getLastPlayTime().getMonth()==d.getMonth()&&u.getLastPlayTime().getYear()==d.getYear())) {//判断上一次游戏时间是否是上一天，如果超过一天则重置留机次数
//				club.pinea.mapper.updateStaySeatTime(3,u.getId());
//			}
            userMapper.updateUserIp(u.getId(), ip, u.getStaySeatTime());
        } catch (Exception e) {
            logger.error("修改id为" + u.getId() + "的登录信息失败，异常信息：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public int userRegister(User u) {
        int result = 0;
        try {
            result = userMapper.userRegister(u);
            userMapper.userInfoRegister(u);
            logger.info(u.getUsername() + "用户注册成功！注册信息为：" + u.toString());
        } catch (Exception e) {
            logger.error(u.getUsername() + "用户注册失败，失败信息为：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int userCount(String beInvited) {
        int count = 0;
        try {
            count = userMapper.userCount(beInvited);
            return count;
        } catch (Exception e) {
            logger.error("查找邀请码" + beInvited + "的时候出现异常：" + e.getMessage());
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean verifyName(String name) {
        try {
            return userMapper.verifyName(name) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean adminValidate() {
        try {
            int status = userMapper.adminValidate();
            return status > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void updateControllerValue(int i) {
        try {
            userMapper.updateControllerValue(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Promoter promLogin(String name, String pass) {
        Promoter prom = null;
        try {
            //调用mapper的方法获取user对象比较密码是否一致
            prom = userMapper.selectPromoterByName(name);
            if (prom != null && prom.getPassword().equals(StringUtils.encode(pass + prom.getToken()))) {
                prom.setPassword(null);
                prom.setToken(null);
                return prom;
            } else {
                return null;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int resetPassword(String name, String oldPass, String newPass) {
        User u = null;
        try {
            //调用mapper的方法获取user对象比较密码是否一致
            u = userMapper.selectUserByName(name);
            if (u != null && u.getPassword().equals(StringUtils.encode(oldPass + u.getToken()))) {
                u.setPassword(StringUtils.encode(newPass + u.getToken()));
                return userMapper.updateUserById(u);
            } else {
                return 0;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return 0;
        }
    }


    @Override
    public void UserLogout(int id, int status) {
        try {
            userMapper.userLoginout(id, status);
            logger.info("id为" + id + "的用户设置登录状态为离线");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("id为：" + id + "的用户断开连接异常：" + e.getMessage());
        }
    }

    @Override
    public String getUserName(int id) {
        String name = null;
        try {
            User u = userMapper.selectUserById(id);
//			if(u.getStatus()!=3) {
//				throw new IllegalArgumentException("登录状态异常！");
//			}
            userMapper.updateUserStatus(1, id);
            name = u.getUsername();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }

    @Override
    public long getMoneyById(int userId) {
        long d = 0;
        try {
            d = userMapper.getMoneyById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据用户id查询，用户账户金额，异常。");
        }
        return d;
    }

    @Override
    public void updateTimeOutUser() {
        try {
            userMapper.updateTimeOutUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateOutBoundsGameTime() {
        try {
            userMapper.updateOutBoundsUserInfoGameTime();
            userMapper.updateOutBoundsSeatsInfoGameTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int selectStaySeatTimeById(int userId) {
        try {
            User u = userMapper.selectUserById(userId);
            if (u == null) {
                throw new IllegalArgumentException("参数错误，id不正确，不能找到用户id：" + userId);
            }
            if (u.getStaySeatTime() > 0) {
                userMapper.updateStaySeatTime(u.getStaySeatTime() - 1, userId);
                return u.getStaySeatTime() - 1;
            } else {
                throw new IllegalArgumentException("您今日留机次数已用完！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public void updateMoney(double money, int userId) throws SQLException {
        if (userId == 0) {
            throw new IllegalArgumentException("参数异常，id不能为0");
        }
        int result = userMapper.updateMoney(money, userId);
        if (result > 0) {
            logger.info("id为：" + userId + "的用户进行了金币更新操作，金币增加：" + money);
        } else {
            logger.info("id为：" + userId + "的用户进行金币更新操作失败");
        }
    }


    @Override
    public SeatsInfo getSeatsInfo(int roomId, int seatId, int payScore) throws SQLException {
        try {
            SeatsInfo seat = null;
            seat = userMapper.getSeatsInfo(seatId);
            userMapper.updateSeatInfo(payScore, 0, seatId);
            return seat;
        } catch (Exception e) {
            logger.debug("获取座位信息错误：" + e.getMessage());
            return null;
        }
    }

    @Override
    public UserInfo getUserInfo(int userId) throws SQLException {
        return userMapper.getUserInfo(userId);
    }

    @Override
    public User getUserById(int userId) throws SQLException {
        return userMapper.getUserById(userId);
    }

    @Override
    public void updateUserInfo(int score, int gameScore, int id) throws SQLException {
        userMapper.updateUserInfo(score, gameScore, id);
    }

    @Override
    public void updateSeatInfo(int score, int gameScore, Integer seatId) throws SQLException {
        userMapper.updateSeatInfo(score, gameScore, seatId);
    }


    @Override
    public void updateUserAndSeatInfo(int checkId, int id, byte b, int roomId, int seatId, int score, int resetNum) {
        userMapper.updateCheckId(checkId, id, score);
        userMapper.updateSeatListNum(b, seatId, score, resetNum);
    }

    @Override
    public void updateSeatDoubleScore(int score, int gameScore, int seatId) {
        userMapper.updateSeatDoubleScore(score, gameScore, seatId);
    }

    @Override
    public Map<String, Object> selectSeatRecords(int seatId) {
        return userMapper.selectSeatRecords(seatId);
    }

    @Override
    public void addRecords(int userId, Integer seatId, int i, int gameScore, int result, int j, int multiplyPower) {
        userMapper.addRecords(userId, seatId, i, gameScore, result, j, multiplyPower);
    }

    @Override
    public double getUserMoneyById(int userId) {
        return userMapper.selectUserMoneyById(userId);
    }


}
